package com.example.demo.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.SysAttachinfoMapper;
import com.example.demo.mapper.SysAttachstorageMapper;
import com.example.demo.model.entity.SysAttachinfo;
import com.example.demo.model.entity.SysAttachstorage;
import com.example.demo.model.form.FileInfoForm;
import com.example.demo.service.SysAttachService;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * 本地存储服务类
 */
@Data
@Slf4j
@Component
@ConditionalOnProperty(value = "oss.type", havingValue = "db")
@ConfigurationProperties(prefix = "oss.db")
public class SysAttachDbImplService implements SysAttachService {

    @Autowired
    private SysAttachinfoMapper sysAttachinfoMapper;
    @Autowired
    private SysAttachstorageMapper sysAttachstorageMapper;
    @Autowired
    private ThreadPoolTaskScheduler schedulerTaskExecutor;
    /**
     * 上传文件方法
     *
     * @param file 表单文件对象
     * @return 文件信息
     */
    @Override
    public FileInfoForm uploadFile(MultipartFile file) {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        String attachguid = IdUtil.simpleUUID();
        // 生成uuid
        String fileName = attachguid + "." + suffix;
        // try-with-resource 语法糖自动释放流
        try(InputStream inputStream = file.getInputStream()) {
            byte[] bytes = file.getBytes();
            SysAttachinfo attachinfo = new SysAttachinfo();
            attachinfo.setAttachguid(attachguid);
            attachinfo.setAttachfilename(originalFilename);
            attachinfo.setContenttype(file.getContentType());
            attachinfo.setAttachlength(bytes.length);
            attachinfo.setStoragetype("db");
            attachinfo.setUpdatetime(new Date());
            SysAttachstorage attachstorage = new SysAttachstorage();
            attachstorage.setAttachguid(attachinfo.getAttachguid());
            attachstorage.setAttachfilename(originalFilename);
            attachstorage.setContenttype(file.getContentType());
            attachstorage.setDocumenttype("");
            attachstorage.setContent(bytes);
            attachstorage.setClientguid("");
            sysAttachinfoMapper.insert(attachinfo);
            sysAttachstorageMapper.insert(attachstorage);
            // 获取文件访问路径，因为这里是本地存储，所以直接返回文件的相对路径，需要前端自行处理访问前缀
            FileInfoForm fileInfo = new FileInfoForm();
            fileInfo.setName(originalFilename);
            fileInfo.setUrl("/api/v1/file/download?attachGuid=" + attachguid);
            fileInfo.setAttachGuid(attachguid);
            return fileInfo;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败");
        }


    }

    /**
     * 删除文件
     *
     * @param attachguid 附件标识
     * @return 是否删除成功
     */
    @Override
    public boolean deleteFile(String attachguid) {
        int i = sysAttachinfoMapper.deleteById(attachguid);
        int i1 = sysAttachstorageMapper.deleteById(attachguid);
        // 延迟双删
        schedulerTaskExecutor.schedule(() -> {
            sysAttachinfoMapper.deleteById(attachguid);
            sysAttachstorageMapper.deleteById(attachguid);
        }, Instant.now().plusSeconds(3));
        return i > 0 && i1 > 0;
    }

    @Override
    public InputStream downloadFile(String attachGuid) {
        SysAttachstorage attachstorage = sysAttachstorageMapper.selectOneById(attachGuid);
        if(attachstorage == null) {
            throw new ServiceException("文件不存在，附件标识 "+ attachGuid);
        }
        return new ByteArrayInputStream(attachstorage.getContent());
    }
    @Override
    public void updateFileClientinfo(List<String> attachGuidList, String clientGuid) {
        List<SysAttachinfo> attachList = sysAttachinfoMapper.selectListByQuery(QueryWrapper.create().in("attachguid", attachGuidList));
        for (SysAttachinfo attachinfo : attachList) {
            attachinfo.setClientguid(clientGuid);
            sysAttachinfoMapper.update(attachinfo);
        }
    }

    @Override
    public void updateFileClientinfo(List<String> attachGuidList, String clientGuid, String clientTag) {
        List<SysAttachinfo> attachList = sysAttachinfoMapper.selectListByQuery(QueryWrapper.create().in("attachguid", attachGuidList));
        for (SysAttachinfo attachinfo : attachList) {
            attachinfo.setClientguid(clientGuid);
            attachinfo.setClienttag(clientTag);
            sysAttachinfoMapper.update(attachinfo);
        }
    }
}
